package cn.sky.demo.sso;

import cn.sky.demo.service.UserService;
import cn.sky.demo.test.User;
import cn.sky.demo.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/auth0")
public class AuthController {

       @Autowired
       private UserService userService;
       
       @Autowired
       private JwtUtil jwtUtil;
       
       @PostMapping("/login")
       public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
             // 验证用户凭证
            User user= userService.authenticate(
                        loginRequest.getUsername(),  
                        loginRequest.getPassword()
            );
             
             if  (user ==  null) {
                   return  ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                              .body(new ErrorResponse("Invalid credentials"));
            }
             
             // 生成JWT
            String jwt= jwtUtil.generateToken(user);
             
             // 设置刷新令牌（可选）
            String refreshToken= UUID.randomUUID().toString();
            userService.saveRefreshToken(user.getId(), refreshToken,  30);  // 30天有效期
             
             // 返回Token
             return  ResponseEntity.ok(new JwtResponse(jwt, refreshToken));
      }
       
       @PostMapping("/refresh")
       public  ResponseEntity<?> refreshToken(@RequestBody  RefreshTokenRequest request) {
            String refreshToken= request.getRefreshToken();
             
             // 验证刷新令牌
            User user= userService.findUserByRefreshToken(refreshToken);
             if  (user ==  null) {
                   return  ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                              .body(new ErrorResponse("Invalid refresh token"));
            }
             
             // 生成新的JWT
            String newToken= jwtUtil.generateToken(user);
             
             return  ResponseEntity.ok(new JwtResponse(newToken, refreshToken));
      }
       
       @PostMapping("/validate")
       public  ResponseEntity<?> validateToken(@RequestBody  TokenValidationRequest request) {
            String token= request.getToken();
             
             if  (!jwtUtil.validateToken(token)) {
                   return  ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                              .body(new ErrorResponse("Invalid token"));
            }
             
             // 提取用户信息
            Claims claims= jwtUtil.extractAllClaims(token);
            Map<String, Object> userInfo = new HashMap<>(claims);
             
             return  ResponseEntity.ok(userInfo);
      }
       
       @PostMapping("/logout")
       public  ResponseEntity<?> logout(@RequestBody  LogoutRequest request) {
             // 删除刷新令牌
            userService.removeRefreshToken(request.getRefreshToken());
             
             // JWT本身无法撤销，客户端需要丢弃令牌
             return  ResponseEntity.ok(new SuccessResponse("Logout successful"));
      }
}